package day9;

import org.junit.Test;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;

public class getAgeByIdCard {
    public int parseId(String id){
        // 1. 格式校验
        String idRegex="^\\d{17}[0-9Xx]$";
        if(!id.matches(idRegex)){
            throw new RuntimeException("身份证格式不正确");
        }

        // 2. 截取出生的日期
        String birth = id.substring(6, 14); // 例如: 20020812

        // 3. 日期的计算
        // 字符串转LocalDate
        LocalDate birthDate = LocalDate.parse(birth, DateTimeFormatter.ofPattern("yyyyMMdd"));

        // 获得现在的时间
        LocalDate now = LocalDate.now();

        // 计算年龄
        Period period = Period.between(birthDate, now);
        int age = period.getYears();

        return age; // 返回计算出的年龄
    }

    @Test
    public void test02() {
        getAgeByIdCard calculator = new getAgeByIdCard();
        try {
            String idCard = "430111200208120012";
            int age = calculator.parseId(idCard);
            System.out.println("身份证：" + idCard);
            System.out.println("年龄为：" + age);
        } catch (Exception e) {
            System.out.println("错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
